/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { MetadataTree } from '@/service/modules/sqlconsole/types'
import { HomeOutlined } from '@vicons/antd'
import {
  Add24Regular,
  ArrowSync16Regular,
  Mail24Regular,
  Search12Regular
} from '@vicons/fluent'
import { useDebounce } from '@vueuse/core'
import { NButton, NIcon, NInput, NSpin, NTree } from 'naive-ui'
import { defineComponent, h, PropType, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import styles from '../index.module.scss'
import { useTreeData } from './use-tree-data'

const props = {
  loading: {
    type: Boolean,
    default: true
  },
  tree: {
    type: Array as PropType<MetadataTree[]>,
    default: () => []
  },
  refresh: {
    type: Function as PropType<() => void>,
    default: () => {}
  },
  onLoad: {
    type: Function as any,
    default: () => {}
  }
}

const TreeData = defineComponent({
  name: 'tree-data',
  props,
  emits: ['click'],
  setup(props) {
    const { t } = useI18n()

    const { renderTreePrefix, returnBack, filterTree, selectTree } =
      useTreeData()
    const $route = useRoute()

    const searchString = ref<string>('')
    const debounced = useDebounce(searchString, 500)
    const filteredTree = ref<MetadataTree[]>([])
    const expandedKeys = ref<string[]>(['1'])
    const selectedKeys = ref<string[]>([])

    watch(
      [() => props.tree, () => debounced.value, () => props.loading],
      () => {
        if (!props.loading && props.tree.length !== 0) {
          filteredTree.value = filterTree(props.tree, debounced.value as string)
          expandedKeys.value = [props.tree[0].label]
          // need to expand tree, in order to highlight tree node
          selectedKeys.value = $route.params.dbId
            ? [
                props.tree?.filter(
                  (item) => item.label === $route.params.dbId
                )[0].key + ''
              ]
            : [props.tree[0].key + '']
        }
      }
    )

    watch(
      () => $route.params.dbId,
      () => {
        props.tree.forEach((item: MetadataTree) => {
          if (item.title === $route.params.dbId) {
            selectedKeys.value = [item.key + '']
          }
        })
      },
      {
        immediate: true
      }
    )

    return {
      t,
      searchString,
      filteredTree,
      returnBack,
      renderTreePrefix,
      selectTree,
      onload
    }
  },
  render() {
    return (
      <div class={styles.dataTree}>
        <div class={styles.optionHeader}>
          <NButton
            type='default'
            style={styles.button}
            onClick={this.returnBack}
          >
            <NIcon class={styles.icon}>
              <HomeOutlined />
            </NIcon>
          </NButton>
          <span class={styles.title}>{this.t('explore.db_table')}</span>
          <span class={styles.refresh} onClick={this.refresh}>
            <NIcon class={styles.icon}>
              <ArrowSync16Regular />
            </NIcon>
            <span class={styles.tip}>{this.t('common.refresh')}</span>
          </span>
        </div>
        <div class={styles.createDatabase}>
          <NButton type='primary' style={styles.button}>
            <NIcon class={styles.icon}>
              <Add24Regular />
            </NIcon>
            {this.t('database.create_database')}
          </NButton>
          <NInput
            type='text'
            v-model={[this.searchString, 'value']}
            placeholder={this.t('database.search_database')}
            clearable
          >
            {{
              prefix: () =>
                h(NIcon, null, { default: () => h(Search12Regular) })
            }}
          </NInput>
        </div>
        {this.loading ? (
          <NSpin class={styles.loading} size='small' />
        ) : (
          <div class={styles.treeContent}>
            {this.filteredTree.length === 0 ? (
              <div class={styles.default}>
                <NIcon class={styles.icon}>
                  <Mail24Regular />
                </NIcon>
                {this.t('database.null_database')}
              </div>
            ) : (
              <NTree
                block-line
                data={this.filteredTree}
                selectable={true}
                onLoad={this.onLoad}
                renderPrefix={this.renderTreePrefix}
                onUpdateSelectedKeys={this.selectTree}
              ></NTree>
            )}
          </div>
        )}
      </div>
    )
  }
})

export default TreeData
